const app = getApp();
const Controller = require('../controllers/controllers').controller;
const manage = wx.getBackgroundAudioManager()
Page({
  data: {
    title:'达人榜',
    mode: 1,
    play: 1,
    ismoth: false,
    albumnavcurrent: 0,
    page: 1,
    pageSize: 10,
    type: 1,
    myRankdata: "",
    rankPagedata: [],
    isEnd: false,
    userInfo: '',
    appinfodata: '',
    mypositionbool: true,
    rank: 0,
    isFixedTop: false,
    navHeight: 66,
    isCheckCollect: null, //检测是否点赞收藏返回来的id
    userInfos:'',
    playMod: 1,
    isloading:false,
    isIphoneX:false,
  },
  onShow() {
    this.setData({
      playMod: app.globalData.playMod,
      play:app.globalData.play
    })
    this.Dialog = this.selectComponent('#Dialog');
    this.setData({
      navHeight: app.globalData.navHeight,
      ismoth: false,
      albumnavcurrent: 0,
      page: 1,
      pageSize: 10,
      type: 1,
      myRankdata: "",
      rankPagedata: [],
      isEnd: false,
      userInfo: '',
      appinfodata: '',
      mypositionbool: true,
      rank: 0,
      isFixedTop: false,
      weekrank:0,
      mothrank:0,
      
    })
    if (!wx.getStorageSync('logintoken')) {
      app.ToLogin()
    } else {
      this.myRank()
      this.myRank(2)
      this.setData({
        userInfo: wx.getStorageSync('userInfo')
      })
    }
    this.rankPage()
    // 检测收藏
    this.checkCollect();
    this.appinfo()
    this.getUserInfos()
    let isIphoneX = app.globalData.isIphoneX;
    this.setData({
      isIphoneX: isIphoneX
    })
  },
  appinfo() {
    Controller.info({
      key: 'key-rank-desc'
    }).then(res => {
      this.setData({
        appinfodata: res.data.baseData
      })
    })
  },
  // 获取用户信息
  getUserInfos() {
    let that = this
    Controller.getUserInfo()
      .then(res => {
        console.log('获取用户信息', res)
        if (res.code == 0) {
          let userInfos = res.data.baseData
          that.setData({
            userInfos
          })
          that.toHour(res.data.baseData.listenTimes)
        }
      })
  },
  toHour(seconds,type) {
    if (!seconds) return 0;
    seconds=Number(seconds)
    if(seconds<3600){
      var mins=(seconds/60).toFixed(2)>1?(seconds/60).toFixed(2):1
      type=type?type:'min'
      this.setData({
        listenTimes: mins + type,
        listen:'分钟'
      })

    }else{
      var hour=(seconds/60/60).toFixed(2)
      type=type?type:'h'
      this.setData({
        listenTimes:hour + type,
        listen:'小时'
      })
    }
    
  },
  // 排行榜
  rankPage() {
    Controller.rankPage({
      page: this.data.page,
      pageSize: this.data.pageSize,
      type: this.data.type,
    }).then(res => {
      if (res.data.baseData && res.data.baseData.list && res.data.baseData.list.length > 0) {
        for (let item of res.data.baseData.list) {
          item.followed = 0
        }
        this.setData({
          rankPagedata: this.data.rankPagedata.concat(res.data.baseData.list)
        })
        if (res.data.baseData.lastPage) {
          this.setData({
            isEnd: true
          })
        } else {
          this.setData({
            isEnd: false
          })
        }
      }
      this.setData({isloading:true})
    }).catch(res=>{
      this.setData({isloading:true})
      if(res.code=101){
        
      }
    })
  },
  onReachBottom() {
    if (this.data.isEnd) {
      return;
    } else {
      this.setData({
        page: this.data.page + 1,
      });
      this.rankPage()
    }
  },
  myRank(type) {
    var Ttype=this.data.type || 1
    if(type){
      Ttype=type
    }
    Controller.myRank({
      type: Ttype,
    }).then(res => {
      this.setData({
        myRankdata: res.data.baseData
      })
      if(Ttype==1){
        this.setData({
          weekrank: res.data.baseData.rank
        })
      }
      if(Ttype==2){
        this.setData({
          mothrank: res.data.baseData.rank
        })
      }
    }).catch(res=>{
      if(res.code=101){

      }
    })
  },
  onPageScroll: function (e) { // 获取滚动条当前位置
    if (e.scrollTop > 20) {
      this.setData({
        defaultFix: true
      })
    } else {
      this.setData({
        defaultFix: false
      })
    }
    let query = wx.createSelectorQuery()

    query.select('#lists').boundingClientRect((rect) => {
      let top = rect.top;
      if (top <= this.data.navHeight) {
        this.setData({
          isFixedTop: true
        })
      } else {
        this.setData({
          isFixedTop: false
        })
      }
    }).exec()
  },
  datechange() {
    this.setData({
      ismoth: !this.data.ismoth,
      type: this.data.ismoth ? 1 : 2,
      page: 1,
      pageSize: 10,
      rankPagedata: [],
      mypositionbool: true
    })
    this.rankPage()
  },
  tosearch() {
    wx.navigateTo({
      url: '/pages/Talent/Search/Search'
    })
  },
  share() {
    app.share('',4,'达人榜')
  },
  collect(bool=false) {
    Controller.rankPage({
      page: this.data.page,
      pageSize: this.data.pageSize,
      type: this.data.type,
    }).then(res => {
      if (res.data.baseData && res.data.baseData.list && res.data.baseData.list.length > 0) {
        this.setData({
          rankPagedata: this.data.rankPagedata.concat(res.data.baseData.list)
        })
        if (res.data.baseData.lastPage) {
          this.setData({
            isEnd: true
          })
        } else {
          this.setData({
            isEnd: false
          })
        }
      }
      if(bool && this.data.rankPagedata.length>0){
          this.gomy()
      }
    })
  },
  myposition() {
    if (!wx.getStorageSync('logintoken')) {
      app.ToLogin()
    } else {
      var rank = 0;
      if(this.data.type==1){
        if(this.data.weekrank){
          rank = Number(this.data.weekrank);
        }
      }else{
        if(this.data.mothrank){
          rank = Number(this.data.mothrank);
        }
      }
      var pageSize = 100; 
      this.setData({
        mypositionbool: !this.data.mypositionbool
      })
      if (this.data.mypositionbool) {
        this.setData({
          page: 1,
          pageSize: 10,
          rankPagedata: [],
          isEnd: false,
        })
      } else {
        var page = 1
        if (rank > 19) {
          pageSize = (rank - 19)+100;
          page = 1
        } else {
          pageSize = 100
        }
        this.setData({
          page: page,
          pageSize: pageSize,
          rankPagedata: [],
          isEnd: true,
        })
        
      }
      this.collect(true)
    }
  },
  gomy() {
    var that = this;
    var query = wx.createSelectorQuery().in(that);
    query.selectViewport().scrollOffset()
    query.select(".mylistsposition").boundingClientRect();
    query.exec(function (res) {
      if (!that.data.mypositionbool) {
        if (res) {
          var miss = res[0].scrollTop + res[1].top - 120;
          if(that.data.isIphoneX){
            miss=miss-34
          }
          setTimeout(() => {
            wx.pageScrollTo({
              scrollTop: miss,
              duration: 300
            })
          }, 200)
        }
      }else{
        setTimeout(() => {
          wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
          })
        }, 200)
      }
    })
  },
  follow(e) {
    var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;
    Controller.follow({
      followedUserId: id
    }).then(res => {
      this.Dialog.ShowDialog({
        type: 'Message',
        title: '关注成功！'
      });
      this.data.rankPagedata[index].followed = 1
      this.setData({
        rankPagedata: this.data.rankPagedata
      })
    }).catch(res => {
      if (res.code = -1) {
        this.data.rankPagedata[index].followed = 1
        this.setData({
          rankPagedata: this.data.rankPagedata
        })
      }
    })
  },
  like() {
    let that = this;
    if (that.data.isCheckCollect) {
      that.delCollect(that.data.isCheckCollect)
    } else {
      that.addCollect()

    }
  },
  // 添加收藏 --达人榜的添加收藏传0
  addCollect() {
    Controller.collect({
        type: 4,
        rid: 0,
        bodyId: 0
      })
      .then(res => {
        app.updateScore(9)
        console.log('添加收藏', res)
        this.checkCollect();
      })
  },
  // 取消收藏
  delCollect(ids) {
    Controller.delCollect({
        ids
      })
      .then(res => {
        console.log('取消收藏', res)
        this.checkCollect();
      })
  },
  // 检测是否点赞收藏 rid传个0
  checkCollect() {
    Controller.checkCollect({
        type: 4,
        rid: 0,
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        console.log(res)
        if (res.code == 0) {
          this.setData({
            isCheckCollect: res.data.baseData
          })
        }
      })
  },
  playall(e) {
    // var index=0;
    // if(e.currentTarget.dataset.index){
    //   index=e.currentTarget.dataset.index
    // }
    // app.globalData.currentIndex=index
    // app.globalData.songlist=this.data.audioListdata
    // this._init()

    var userId=e.currentTarget.dataset.id
    app.globalData.currentIndex=0
    app.globalData.songlist=[]
    wx.navigateTo({
      url: "/pages/Playing/Playing?albumnavcurrent=0&userId=" +userId 
    })
  },

  _init() {
    let currentIndex = app.globalData.currentIndex || 0;
    let songslist = (app.globalData.songlist.length && app.globalData.songlist)
    let currentSong = app.globalData.songlist[app.globalData.currentIndex] || (songslist && songslist[app.globalData.currentIndex])
    let duration = currentSong && currentSong.duration
    this.setData({
      currentSong: currentSong,
      duration: duration,
      songslist: songslist,
      currentIndex: currentIndex
    })
    this._getPlayUrl(currentSong)
  },
  // 获取播放地址
  _getPlayUrl(currentSong) {
    const _this = this
    console.log('currentSong',currentSong)
    if (currentSong && currentSong.audioUrl) {
      _this._createAudio(currentSong)
    } else {
      manage.stop()
      wx.showToast({
        title: '本歌曲暂时不能播放。请切换下一首',
        icon: 'none'
      })
    }
  },
  // 创建播放器
  _createAudio(currentSong) {
    if(!manage.src){
      wx.playBackgroundAudio({
        dataUrl: currentSong.audioUrl,
        title: currentSong.title,
        coverImgUrl: currentSong.imgUrl
      })
    }
    // 监听音乐播放。
    wx.onBackgroundAudioPlay(() => {
      this.setData({
        play: 2
      })
      app.globalData.play=2
      app.currentSong=currentSong
      app.play(currentSong.id)
    })
    // 监听音乐暂停。
    wx.onBackgroundAudioPause(() => {
      this.setData({
        play: 1
      })
      app.globalData.play=1
      // 更新收听时长接口
      Controller.uploadListenTimes({
        seconds: parseInt(this.data.currentTime)
      })
      .then(res => {

      })
    })
    // 监听音乐停止。
    wx.onBackgroundAudioStop(() => {
      if (this.data.playMod === SINGLE_CYCLE_MOD) {
        this._init()
        return
      }
      // 更新收听时长接口
      Controller.uploadListenTimes({
        seconds: parseInt(this.data.currentTime)
      })
      .then(res => {

      })
      this.next()
    })
  },
  onTimeUpdate(time){
    // 监听播放拿取播放进度
    
    if(time){
      manage.seek(time);
    }
    manage.onTimeUpdate(() => {
      const currentTime = manage.currentTime;
      const duration=manage.duration
      this.setData({
        currentTime: this._formatTime(currentTime),
        duration:this._formatTime(duration),
        percent: currentTime / duration*100
      })
    })
  },
  prev() {
    app.globalData.currentIndex = this.getNextIndex(false)
    this._init()
  },
  next() {
    app.globalData.currentIndex = this.getNextIndex(true)
    this._init()
  },
  getNextIndex(nextFlag) {
    let ret,
        currentIndex = app.globalData.currentIndex,
        mod = this.data.playMod,
        len = this.data.songslist.length
    if (mod === RANDOM_MOD) {
      ret = randomNum(len)
    } else {
      if (nextFlag) {
        ret = currentIndex + 1 == len ? 0 : currentIndex + 1
      } else {
        ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
      }
    }
    return ret
  },
  togglePlaying(e) {
    wx.getBackgroundAudioPlayerState({
      success(res) {
        var status = res.status
        if (status == 1) {
          wx.pauseBackgroundAudio()
        } else {
          wx.playBackgroundAudio()
        }
      }
    })
  },
  onShareAppMessage: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·达人榜',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
  onShareTimeline: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·达人榜',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
})